package artid.com.arttogoa;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import artid.com.arttogoa.R;

import artid.com.arttogoa.app.ArtWorkApp;
import artid.com.arttogoa.barcode.Cache;
import artid.com.arttogoa.parser.NormalItem;
import artid.com.arttogoa.util.AppUtil;
import artid.com.arttogoa.util.MySharedPreferences;
import artid.com.arttogoa.util.ToastUtil;
import artid.com.arttogoa.volley.VolleyBasic;
import artid.com.arttogoa.volley.VolleyCallback;
import artid.com.arttogoa.volley.VolleyData;
import artid.com.arttogoa.volley.VolleyMap;
import com.android.volley.VolleyError;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.util.Pair;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

/**
 * 
 *    
 * 项目名称：ArtworkArtA   
 * 类名称：MessageActivity   
 * 类描述：消息管理  
 * 创建人：耿卫斌  
 * 创建时间：2016年5月16日 下午2:27:09      
 *
 */
public class MessageActivity extends BaseActivity implements OnClickListener {
	private RelativeLayout mNotice, mReply, mInquiry;
	private Intent mIntent;
	private TextView reply,xunjiaNum;
	private ImageView systemUnreadMessage_icon,hxUnreadMessage_icon,replyUnreadMessage_icon;
	private List<EMConversation> conversationList;
	private  int unreadMesageNum=0;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_message);
		setContent(this, getIntent());
		ArtWorkApp.getInstance().addActivity(this);
		// 注册当前广播
		IntentFilter filter = new IntentFilter("com.MessageActivity.receiver");
		registerReceiver(broadcastReceiver, filter);
		conversationList=new ArrayList<EMConversation>();
		mNotice = (RelativeLayout) findViewById(R.id.notice_layout);
		mReply = (RelativeLayout) findViewById(R.id.reply_layout);
		mInquiry = (RelativeLayout) findViewById(R.id.inquiry_layout);
		reply=(TextView) findViewById(R.id.MessageActivity_reply);
		mTittle = (TextView) findViewById(R.id.title_text);
		xunjiaNum=(TextView) findViewById(R.id.Message_xunjiaNum);
		systemUnreadMessage_icon=(ImageView) findViewById(R.id.Message_SystemUnreadMessage);
		hxUnreadMessage_icon=(ImageView) findViewById(R.id.Message_hxUnreadMessage);
		replyUnreadMessage_icon=(ImageView) findViewById(R.id.Message_replyUnreadMessage);
		mTittle.setText("消息");
		setBack();
		mNotice.setOnClickListener(this);
		mReply.setOnClickListener(this);
		mInquiry.setOnClickListener(this);

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		getSystemAndHxNum();
		getMesaageNum();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.notice_layout:// 通知
			mIntent=new Intent(MessageActivity.this,NoticeActivity.class);
			startActivity(mIntent);
			break;
		case R.id.reply_layout:// 回复
			mIntent=new Intent(MessageActivity.this,ReplyActivity.class);
			startActivity(mIntent);
			break;
		case R.id.inquiry_layout:// 询价
			mIntent=new Intent(MessageActivity.this,InquiryActivity.class);
			startActivity(mIntent);
			break;

		default:
			break;
		}
	}

	/**
	 * 获取系统/环信条数
	 */
	private void getSystemAndHxNum(){
		unreadMesageNum=0;
		conversationList.clear();
		conversationList.addAll(loadConversationsWithRecentChat());
		for (int i = 0; i < conversationList.size(); i++) {
			EMConversation conversation = EMClient.getInstance().chatManager().getConversation(conversationList.get(i).conversationId());
			unreadMesageNum=conversation.getUnreadMsgCount()+unreadMesageNum;
		}
		if(unreadMesageNum!=0){
			//判断环信是否有未读消息
			hxUnreadMessage_icon.setVisibility(View.VISIBLE);
		}else{
			hxUnreadMessage_icon.setVisibility(View.GONE);
		}

		if("1".equals(MainActivity.isSystemPush)){
			// 判断友盟是否有未读消息(系统/收款/订单签收/消息)
			systemUnreadMessage_icon.setVisibility(View.VISIBLE);
		}else{
			systemUnreadMessage_icon.setVisibility(View.GONE);
		}

		if("true".equals(MySharedPreferences.getMySharedPreferences(mContext).getValue("isReplyPush"+ AppUtil.getUser().getUid(), "false"))){
			replyUnreadMessage_icon.setVisibility(View.VISIBLE);
		}else{
			replyUnreadMessage_icon.setVisibility(View.GONE);
		}
		xunjiaNum.setText("询价("+unreadMesageNum+")");
	}


	/**
	 * 艺术家未回复的消息数量
	 */
	private void getMesaageNum(){
		VolleyBasic.getInstance(MessageActivity.this).post(Cache.messageList,
				VolleyMap.getInstance().messageList(), NormalItem.class,new VolleyCallback() {
			public void onSuccess(VolleyData vd) {
				// TODO Auto-generated method stub
				System.out.println(vd.getJson());
				NormalItem bean=(NormalItem) vd.getData();
				String data = bean.data;
				reply.setText("回复("+data+")");
			}
			public void onError(VolleyError volleyError) {
				ToastUtil.toast(mContext, "服务器连接失败，请稍后重试");
			}
		});
	}

	/**
	 * 获取所有会话
	 * 
	 * @param context
	 * @return +
	 */
	private List<EMConversation> loadConversationsWithRecentChat() {
		// 获取所有会话，包括陌生人
		Map<String, EMConversation> conversations = EMClient.getInstance()
				.chatManager().getAllConversations();
		// 过滤掉messages size为0的conversation
		/**
		 * 如果在排序过程中有新消息收到，lastMsgTime会发生变化 影响排序过程，Collection.sort会产生异常
		 * 保证Conversation在Sort过程中最后一条消息的时间不变 避免并发问题
		 */
		List<Pair<Long, EMConversation>> sortList = new ArrayList<Pair<Long, EMConversation>>();
		synchronized (conversations) {
			for (EMConversation conversation : conversations.values()) {
				if (conversation.getAllMessages().size() != 0) {
					sortList.add(new Pair<Long, EMConversation>(conversation
							.getLastMessage().getMsgTime(), conversation));
				}
			}
		}
		try {
			// Internal is TimSort algorithm, has bug
			sortConversationByLastChatTime(sortList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		List<EMConversation> list = new ArrayList<EMConversation>();
		for (Pair<Long, EMConversation> sortItem : sortList) {
			list.add(sortItem.second);
		}
		for (int i = 0; i < list.size(); i++) {
			Log.d("log", "环信会话列表：" + list.get(i).getLastMessage().toString());
		}

		return list;
	}

	/**
	 * 根据最后一条消息的时间排序
	 * 
	 * @param usernames
	 */
	private void sortConversationByLastChatTime(
			List<Pair<Long, EMConversation>> conversationList) {
		Collections.sort(conversationList,
				new Comparator<Pair<Long, EMConversation>>() {
			@Override
			public int compare(final Pair<Long, EMConversation> con1,
					final Pair<Long, EMConversation> con2) {

				if (con1.first == con2.first) {
					return 0;
				} else if (con2.first > con1.first) {
					return 1;
				} else {
					return -1;
				}
			}

		});
	}

	// 对开始接单的广播监听
	BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

		@Override  
		public void onReceive(Context context, Intent intent) {  
			// TODO Auto-generated method stub  
			if(intent.getBooleanExtra("UmengPush", false)==true){
				// 友盟是否有消息(系统/收款/订单签收/消息)
				if("0".equals(intent.getStringExtra("PushType")) || "2".equals(intent.getStringExtra("PushType")) || "4".equals(intent.getStringExtra("PushType"))
						|| "9".equals(intent.getStringExtra("PushType")) ){
					MainActivity.isSystemPush="1";
					systemUnreadMessage_icon.setVisibility(View.VISIBLE);
					getSystemAndHxNum();
				}else if("1".equals(intent.getStringExtra("PushType"))){
					replyUnreadMessage_icon.setVisibility(View.VISIBLE);
					getMesaageNum();
				}
			}
			if(intent.getBooleanExtra("HXPush", false)==true){
				getSystemAndHxNum();
				hxUnreadMessage_icon.setVisibility(View.VISIBLE);
			}
		}
	};

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		// 关闭广播
		unregisterReceiver(broadcastReceiver);
	}

}
